package com.sywb.chuangyebao.view.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.sywb.chuangyebao.R;
import com.umeng.analytics.MobclickAgent;

import org.bining.footstone.AppComponent;
import org.bining.footstone.mvp.IFragment;
import org.bining.footstone.mvp.IPresenter;
import org.bining.footstone.mvp.IView;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseDialogFragment<T extends IPresenter> extends DialogFragment implements IFragment, IView, View.OnClickListener {

    protected Activity mActivity;
    protected IView iView;

    protected T mPresenter;

    protected View rootView;

    private Unbinder unbinder;

    protected boolean isOnClick = true;
    protected List<Integer> noLinitClicks;
    protected long clickSleepTime = 300;
    protected long oldClickTime;

    // 标识fragment视图已经初始化完毕
    protected boolean isViewPrepared;
    // 标识已经触发过懒加载数据
    protected boolean hasFetchData;

    protected OnItemListener onItemListener;

    protected static Bundle getBundle(Object... pramars) {
        Bundle bundle = new Bundle();
        if (pramars != null && pramars.length > 0) {
            for (int i = 0; i < pramars.length; i++) {
                bundle.putSerializable("p" + i, (Serializable) pramars[i]);
            }
        }
        return bundle;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(android.support.v4.app.DialogFragment.STYLE_NORMAL, R.style.common_dialog_activity);
        mActivity = getActivity();
        iView = (IView) getActivity();
        mPresenter = getT(this, 0);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Dialog dialog = getDialog();
        if (dialog != null) {
            // dialog.getWindow().setDimAmount(0.0F);
            if (setScreenPosition()) {
                dialog.getWindow().setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
            } else {
                dialog.getWindow().setGravity(Gravity.CENTER);
            }
            dialog.getWindow().setWindowAnimations(R.style.anim_bottom_up_style);
            // dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            // dialog.setCanceledOnTouchOutside(true);
            // dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            // WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
            // params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
            // params.windowAnimations = R.style.bottomSheet_animation;
            // getDialog().getWindow().setAttributes(params);

            // 设置宽度顶满屏幕,无左右留白
            // DisplayMetrics dm = new DisplayMetrics();
            // getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            // getDialog().getWindow().setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);

//        getDialog().setCancelable(false);// dialog弹出后会点击屏幕或物理返回键，dialog不消失
//        getDialog().setCanceledOnTouchOutside(false);// dialog弹出后会点击屏幕，dialog不消失；点击物理返回键dialog消失
//        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
//            @Override
//            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                if (keyCode == KeyEvent.KEYCODE_BACK) {
//                    return true;
//                }
//                return false;
//            }
//        });

        }

        View view = initRootView(inflater, container, savedInstanceState);
        if (view == null) {
            view = inflater.inflate(getLayoutId(savedInstanceState), container, false);
        }
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rootView = view;
        initView(view, savedInstanceState);
        isViewPrepared = true;
        if (getUserVisibleHint() && !hasFetchData && isViewPrepared) {
            hasFetchData = true;
            initPresenter();
        }

        if (!setCancelable()) {
            getDialog().setCancelable(false);
        }

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && !hasFetchData && isViewPrepared) {
            hasFetchData = true;
            initPresenter();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mActivity == null) {
            mActivity = getActivity();
        }
        if (iView == null) {
            iView = (IView) getActivity();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getName());
        if (isMatchParent()) {
            setWindowMatch();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getName());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hasFetchData = false;
        isViewPrepared = false;
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        mPresenter = null;
        iView = null;
        mActivity = null;
    }

    @Override
    public void onClick(View v) {
    }

    private void setWindowMatch() {
        WindowManager.LayoutParams p = getDialog().getWindow().getAttributes();
        p.width = RelativeLayout.LayoutParams.MATCH_PARENT;
        p.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
        getDialog().getWindow().setAttributes(p);
    }

    /**
     * 是否横向铺满屏幕
     *
     * @return
     */
    public boolean isMatchParent() {
        return false;
    }

    /**
     * 设置弹出框在屏幕上的位置是否位于底部
     */
    public boolean setScreenPosition() {
        return true;
    }

    public boolean setCancelable() {
        return true;
    }

    /**
     * 是否可以继续执行点击时间
     */
    public boolean isCanClick(View view) {
        if (isOnClick) {
            int newClickView = view.getId();
            if (noLinitClicks != null && noLinitClicks.size() > 0) {
                for (int viewId : noLinitClicks) {
                    if (newClickView == viewId) {
                        return true;
                    }
                }
            }
            long newClickTime = System.currentTimeMillis();
            if ((newClickTime - oldClickTime) < clickSleepTime) {
                return false;
            } else {
                oldClickTime = newClickTime;
            }
            return true;
        }
        return false;
    }

    @Override
    public View initRootView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return null;
    }

    /**
     * 使用懒加载的方式获取数据，仅在满足fragment可见和视图已经准备好的时候调用一次
     */
    @Override
    public void initPresenter() {
        if (mPresenter != null) {
            mPresenter.initPresenter(this);
        }
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
    }

    @Override
    public void setData(Object data) {
    }

    @Override
    public boolean useRxBus() {
        return false;
    }

    @Override
    public Context getContext() {
        try {
            return super.getContext();
        } catch (Exception e) {
            return getActivity();
        }
    }

    @Override
    public FragmentManager getMyFragmentManager() {
        return getChildFragmentManager();
    }

    @Override
    public void showMessage(String message) {
        iView.showMessage(message);
    }

    @Override
    public void showProgress() {
        iView.showProgress();
    }

    @Override
    public void hideProgress() {
        iView.hideProgress();
    }

    @Override
    public void advance(Class<?> cls, Object... params) {
        iView.advance(cls, params);
    }

    @Override
    public void advance(String clsName, Object... params) {
        iView.advance(clsName, params);
    }

    @Override
    public void advance(Intent intent) {
        iView.advance(intent);
    }

    @Override
    public void advanceForResult(Class<?> cls, int requestCode, Object... params) {
        iView.advanceForResult(cls, requestCode, params);
    }

    @Override
    public void advanceForResult(String clsName, int requestCode, Object... params) {
        iView.advanceForResult(clsName, requestCode, params);
    }

    @Override
    public void advanceForResult(Intent intent, int requestCode) {
        iView.advanceForResult(intent, requestCode);
    }

    public void exit() {
        exit(true);
    }

    @Override
    public void exit(boolean isAnim) {
        dismiss();
    }

    /**
     * 获取引用实体
     */
    protected <T> T getT(Object o, int i) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass().getGenericSuperclass())).getActualTypeArguments()[i]).newInstance();
        } catch (Exception ignored) {
        }
        return null;
    }

    /**
     * 获取控件对象
     */
    protected <V extends View> V getView(int viewId) {
        return (V) rootView.findViewById(viewId);
    }

    /**
     * 批量设置控件点击时间
     */
    protected void setOnClick(View... views) {
        for (View view : views) {
            view.setOnClickListener(this);
        }
    }

    public void setOnItemListener(OnItemListener onItemListener) {
        this.onItemListener = onItemListener;
    }

    public interface OnItemListener {
        void onResult(BaseDialogFragment dialogFragment, Object... params);
    }
}
